<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="12">
          <a-form-item label="企业名称" v-bind="validateInfos.businessName">
            <a-input v-model:value="formData.businessName" placeholder="请输入企业名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="企业电话" v-bind="validateInfos.businessPhone">
            <a-input v-model:value="formData.businessPhone" placeholder="请输入企业电话" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="企业税号" v-bind="validateInfos.businessTax">
            <a-input v-model:value="formData.businessTax" placeholder="请输入企业税号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="企业地址" v-bind="validateInfos.businessAddress">
            <a-textarea v-model:value="formData.businessAddress" rows="2" placeholder="请输入企业地址" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户行" v-bind="validateInfos.businessBankName">
            <a-input v-model:value="formData.businessBankName" placeholder="请输入开户行" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="银行账号" v-bind="validateInfos.businessBankAccount">
            <a-input v-model:value="formData.businessBankAccount" placeholder="请输入银行账号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开票类目" v-bind="validateInfos.categoryId">
            <a-cascader placeholder="请选择开票类目" v-model:value="category" :disabled="disabled"
                        :field-names="{ label: 'title', value: 'key' }" v-if="!disabled"
                        :options="options" :show-search="true" @change="handleSelectCategory"/>
            <a-input v-model:value="formData.categoryText" :disabled="disabled" v-else></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开票金额" v-bind="validateInfos.amount">
	          <a-input-number v-model:value="formData.amount" placeholder="开票金额"
                            :style="disabled ? 'width: 100%' : 'width: 35%'" :disabled="disabled"/>
            <span style="margin-left: 10px;" v-if="!disabled">可开票金额：
              <span style="color: red;">${{parseFloat(billCanAmount).toFixed(2)}}</span>
              <a style="margin-left: 10px;" @click="selectAll">全部</a>
            </span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开票类型" v-bind="validateInfos.type">
            <j-dict-select-tag type='radio' stringToNumber="true" v-model:value="formData.type" dictCode="caishui_bill_type" placeholder="请选择开票类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注信息" v-bind="validateInfos.remark">
            <a-input v-model:value="formData.remark" placeholder="请输入右下角备注信息" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="收件类型" v-bind="validateInfos.receivedType">
            <j-dict-select-tag type='radio' stringToNumber="true" v-model:value="formData.receivedType" dictCode="caishui_bill_received_type"
                               placeholder="请选择收件类型" :disabled="disabled" @change="handleReceivedType"/>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.receivedType==2">
          <a-form-item label="收件地址" v-bind="validateInfos.receivedAddress">
            <a-textarea v-model:value="formData.receivedAddress" rows="2" placeholder="请输入收件地址" :disabled="disabled"></a-textarea>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.receivedType==2">
          <a-form-item label="收件人" v-bind="validateInfos.receivedName">
            <a-input v-model:value="formData.receivedName" placeholder="请输入收件人" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.receivedType==2">
          <a-form-item label="收件电话" v-bind="validateInfos.receivedPhone">
            <a-input v-model:value="formData.receivedPhone" placeholder="请输入收件电话" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JCategorySelect from '/@/components/Form/src/jeecg/components/JCategorySelect.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../CaishuiBill.api';
  import { Form, CascaderProps } from 'ant-design-vue';
  import { loadTreeRoot } from "/@/api/common/api";
  import { queryBusinessAccount } from "/@/api/sys/business.api";

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    companyId: '',   
    businessId: '',   
    orderNo: '',   
    businessName: '',   
    businessPhone: '',   
    businessTax: '',   
    businessAddress: '',   
    businessBankName: '',   
    businessBankAccount: '',
    categoryId: '',
    categoryText: '',
    amount: undefined,
    type: 1,
    remark: '',   
    receivedType: 1,
    receivedName: '',
    receivedPhone: '',
    receivedAddress: '',
    checkTime: '',   
    rejectReason: '',   
    electronicInvoice: '',   
    billImg: '',   
    finishTime: '',   
    status: undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const options = ref<CascaderProps['options']>([]);
  const category = ref<any>([]);
  const billCanAmount = ref(0);

  //表单验证
  const validatorRules = {
    businessName: [{ required: true, message: '请输入企业名称!'},],
    businessPhone: [{ required: true, message: '请输入企业电话!'},],
    businessTax: [{ required: true, message: '请输入企业税号!'},],
    businessAddress: [{ required: true, message: '请输入企业地址!'},],
    businessBankName: [{ required: true, message: '请输入开户行!'},],
    businessBankAccount: [{ required: true, message: '请输入银行账号!'},],
    categoryId: [{ required: true, message: '请选择开票类目!'},],
    amount: [{ required: true, message: '请输入开票金额!'}, { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'},],
    type: [{ required: true, message: '请选择开票类型!'},],
    receivedType: [{ required: true, message: '请选择收件类型!'},],
    receivedName: [{ required: false, message: '请输入收件人!'},],
    receivedPhone: [{ required: false, message: '请输入收件电话!'},],
    receivedAddress: [{ required: false, message: '请输入收件地址!'},],
  };
  const { resetFields, validate, validateInfos, clearValidate } = useForm(formData, validatorRules, { immediate: true });

   // 表单禁用
   const disabled = computed(()=>{
      let bool = false;
      if(props.formBpm === true){
        if(props.formData.disabled === false){
          bool = false;
        }else{
          bool =  true;
        }
      }
      bool = props.formDisabled;
      //清除表单验证
      clearValidate();
      return bool;
   });

  onMounted(async () => {
    await loadTreeRoot({pcode:'A02',async: false}).then((res) => {
      options.value = res;
    });
  });

  /**
   * 选择开票栏目事件
   * @param value
   * @param optios
   */
  function handleSelectCategory(value,optios){
    formData.categoryId = value.join('/');
    formData.categoryText = optios[0].title + "*" + optios[1].title;
  }

  /**
   * 选择收件类型事件
   * @param val
   */
  function handleReceivedType(val){
    let bool;
    if(val==1){
      bool = false;
    }else {
      bool = true;
    }
    validatorRules.receivedName = [{ required: bool, message: '请输入收件人!'},];
    validatorRules.receivedPhone = [{ required: bool, message: '请输入收件电话!'},];
    validatorRules.receivedAddress = [{ required: bool, message: '请输入收件地址!'},];
  }

  /**
   * 选择全部开票金额
   */
  function selectAll(){
    formData.amount = billCanAmount.value
  }

  /**
   * 新增
   */
  function add(value) {
    category.value = [];
    billCanAmount.value = value;
    //查询商户信息
    queryBusinessAccount({}).then((res) => {
      formData.businessName = res.result.name;
      formData.businessPhone = res.result.phone;
      formData.businessTax = res.result.tax;
      formData.businessAddress = res.result.address;
      formData.businessBankName = res.result.bankName;
      formData.businessBankAccount = res.result.bankAccount;
      formData.receivedName = res.result.receivedName;
      formData.receivedPhone = res.result.receivedPhone;
      formData.receivedAddress = res.result.receivedAddress;
    });
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, formData);
    });
  }

  /**
   * 编辑
   */
  function edit(record) {
    if(record && record.categoryId){
      category.value = record.categoryId.split('/');
    }
    if(record && record.billCanAmount){
      billCanAmount.value = (parseFloat(record.billCanAmount) + parseFloat(record.amount));
    }else {
      billCanAmount.value = parseFloat(record.amount);
    }
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //数据格式化
    let model = formData;
    if (model.id) {//编辑
       isUpdate.value = true;
       model.updateBy = "";
       model.updateTime = "";
    }else {//新增
       model.createBy = "";
       model.createTime = "";
       model.sysOrgCode = "";
       model.updateBy = "";
       model.updateTime = "";
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
</style>
